package com.mes.spc.controller;

import com.mes.entity.User;
import com.mes.spc.service.EmesqSpcCheckItemConfigService;
import com.yy.base.page.Message;
import com.yy.base.util.StringUtil;
import com.yy.base.util.UserUtil;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("spc/ckConfig")
public class EmesqSpcCheckItemConfigController {
	
	@Autowired
	private EmesqSpcCheckItemConfigService esccs;
	
	@RequestMapping(value="getList", method=RequestMethod.POST)
	@ResponseBody
	public Message getList(HttpServletRequest request) {
		Message msg = new Message();
		String checkItem = request.getParameter("checkItem");
		String checkNo = request.getParameter("checkNo");//编号
		List<Map<String, Object>> list = this.esccs.getList(checkNo,checkItem);
		msg.setData("list", list);
		return msg;
	}
	
	
	@RequestMapping(value="getBaseInfo", method=RequestMethod.POST)
	@ResponseBody
	public Message getBaseInfo(HttpServletRequest request) {
		Message msg = new Message();
		String id = request.getParameter("configId");
		String orgId = (String)request.getSession().getAttribute("orgId");
		if(!StringUtils.isBlank(id)) {
			Map<String, Object> ckConfig = this.esccs.getSpcCkConfigById(id);
			msg.setData("ckConfig", ckConfig);
		}
		List<Map<String, Object>> checkItemList = this.esccs.getCheckItemList(orgId);
		msg.setData("checkItemList", checkItemList);
		return msg;
	}
	
	@RequestMapping(value="save", method=RequestMethod.POST)
	@ResponseBody
	public Message saveConfig(@RequestParam Map<String, Object> param, HttpServletRequest request) {
		Message message = new Message();
		User user = (User)request.getSession().getAttribute(UserUtil.USERSESSION);
		String orgId = (String)request.getSession().getAttribute("orgId");
		param.put("orgId", orgId);
		param.put("clientId", user.getClientId());
		param.put("userId", user.getId());
		String  exceRuleData = (String)param.get("exceRuleData");
		param.remove("exceRuleData");
		int res = 0;
		if(StringUtils.isBlank((String)param.get("configId")) || "undefined".equals((String)param.get("configId"))) {
			String id =  this.esccs.getSysGuid();
			param.put("configId", id);
			res = this.esccs.addConfig(param);
			//保存判异规则
			this.esccs.saveExceRuleData(exceRuleData, id, orgId, user);
		} else {
			res = this.esccs.updateConfig(param);
		}
		if(res > 0) {
			message.setMsg("保存成功！");
		} else {
			message.setMsg("保存失败！");
		}
		return message;
	}
	
	@RequestMapping(value="getErData", method=RequestMethod.POST)
	@ResponseBody
	public Message getErData(HttpServletRequest request, String configId, String graphType) {
		Message message = new Message();
		List<Map<String, Object>> erData = this.esccs.getErData(configId, graphType);
		message.setData("erData", erData);
		return message;
	}
	
	@RequestMapping(value="calControl", method=RequestMethod.POST)
	@ResponseBody
	public Message calControl(HttpServletRequest request, String configId) {
		Message message = new Message();
		try {
			Map<String, Object> calData = this.esccs.calControl(configId,new HashMap<String, String>());
			message.setData("calData", calData);
		} catch (Exception e) {
			message.setErrorMessage(e.getMessage());
			e.printStackTrace();
		}
		return message;
	}
	
	@RequestMapping(value="saveExceRuleData", method=RequestMethod.POST)
	@ResponseBody
	public Message saveExceRuleData(HttpServletRequest request, String exceRuleData, String configId) {
		Message message = new Message();
		User user = (User)request.getSession().getAttribute(UserUtil.USERSESSION);
		String orgId = (String)request.getSession().getAttribute("orgId");
		if(orgId==null)orgId=user.getOrgId();
		this.esccs.saveExceRuleData(exceRuleData, configId, orgId, user);
		message.setMsg("保存成功！");
		return message;
	}
	
	@RequestMapping(value="getBadProductData", method=RequestMethod.POST)
	@ResponseBody
	public Message getBadProductData(HttpServletRequest request, String configId) {
		Message message = new Message();
		List<Map<String, Object>> bpData = this.esccs.getBadProductData(configId);
		List<Map<String, Object>> bpSelData = this.esccs.getBadProductSelData(configId);
		message.setData("bpData", bpData);
		message.setData("bpSelData", bpSelData);
		return message;
	}
	
	
	@RequestMapping(value="saveBadProductData", method=RequestMethod.POST)
	@ResponseBody
	public Message saveBadProductData(HttpServletRequest request, String badProductData, String configId) {
		Message message = new Message();
		User user = (User)request.getSession().getAttribute(UserUtil.USERSESSION);
		String orgId = (String)request.getSession().getAttribute("orgId");
		this.esccs.saveBadProductData(badProductData, configId, orgId, user);
		message.setMsg("保存成功！");
		return message;
	}
	@RequestMapping(value="parseExcelData", method=RequestMethod.POST)
	@ResponseBody
	public Message parseExcelData(HttpServletRequest request, String exceRuleData, String configId, @RequestParam(name="uploadExcel", required=false) MultipartFile uploadExcel) {
		Message message = new Message();
		User user = (User)request.getSession().getAttribute(UserUtil.USERSESSION);
		String orgId = (String)request.getSession().getAttribute("orgId");
		String isSampleData = request.getParameter("isSampleData");
		if(StringUtils.isEmpty(isSampleData)){
			isSampleData = "0";//0 普通数据上传 1 样本数据上传
		}
//		Map<String, Object> ckConfig = this.esccs.getSpcCkConfigById(configId);
//		int sampleSize = Integer.parseInt(ckConfig.get("SAMPLE_VOLUME")+"");//样本数量
		File file = new File(request.getSession().getServletContext().getRealPath("/")+"tempupload/"+ StringUtil.getUUID()+"."+FilenameUtils.getExtension(uploadExcel.getOriginalFilename()));
		if (!file.exists()) {
			File rst = file.getParentFile();
			if (!rst.exists()) {
				rst.mkdirs();
			}
		}
		try {
			file.createNewFile();
			uploadExcel.transferTo(file);
		} catch (IOException e) {
			e.printStackTrace();
		}
		try {
			int scount = this.esccs.handleExcel(user,orgId,configId,isSampleData,file);
			message.setMsg("保存成功！导入数据："+scount+"条");
		} catch (Exception e) {
			e.printStackTrace();
			message.setMsg("保存失败！错误信息："+e.getMessage());
		}

		return message;
	}

	@RequestMapping(value="downloadExcelTemplate", method=RequestMethod.GET)
	@ResponseBody
	public void downloadExcelTemplate(HttpServletResponse response, String configId) {
		this.esccs.downloadExcelTemplate(response,configId);
	}
	
	@RequestMapping(value="deleteSampleData", method=RequestMethod.POST)
	@ResponseBody
	public Message deleteSampleData(String configId) {
		Message message = new Message();
		boolean flag = this.esccs.deleteSampleData(configId);
		if(flag){
			message.setOkMessage("清除成功！");
		}else{
			message.setErrorMessage("清除失败！");
		}
		return message;
	}
	
	@RequestMapping(value="deleteData", method=RequestMethod.POST)
	@ResponseBody
	public Message deleteData(String configId) {
		Message message = new Message();
		boolean flag = this.esccs.deleteData(configId);
		if(flag){
			message.setOkMessage("删除成功！");
		}else{
			message.setErrorMessage("删除失败！");
		}
		return message;
	}
	
	/**
	 * 查看判异结果
	 * @param calcId
	 * @return
	 */
	@RequestMapping(value="viewCheckRs", method=RequestMethod.POST)
	@ResponseBody
	public Message viewCheckRs(String calcId) {
		Message message = new Message();
		Map<String,Object> rsData = this.esccs.viewCheckRs(calcId);
		if(rsData!=null){
			message.setData(rsData);
			message.setOkMessage("清除成功！");
		}else{
			message.setErrorMessage("清除失败！");
		}
		return message;
	}
	
	/**
	 * 处理判异结果
	 * @param request
	 * @param calcId
	 * @param unControlReason
	 * @param handleMethod
	 * @return
	 */
	@RequestMapping(value="handleError", method=RequestMethod.POST)
	@ResponseBody
	public Message handleError(HttpServletRequest request,String calcId,String unControlReason,String handleMethod) {
		Message message = new Message();
		User user = (User)request.getSession().getAttribute(UserUtil.USERSESSION);
		String orgId = (String)request.getSession().getAttribute("orgId");
		boolean flag = this.esccs.handleError(calcId, unControlReason, handleMethod, user);
		if(flag){
			message.setOkMessage("处理成功！");
		}else{
			message.setErrorMessage("处理失败！");
		}
		return message;
	}
}
